import React, { useRef, useState } from 'react'
import { Canvas, useFrame } from '@react-three/fiber'
import { OrbitControls, useCursor } from '@react-three/drei'
import * as THREE from 'three'

// 魔方单个方块组件
function Cube({ position, color, onClick }) {
  const meshRef = useRef()
  const [hovered, setHover] = useState(false)
  
  useCursor(hovered) // 鼠标悬停时显示指针光标
  
  return (
    <mesh
      ref={meshRef}
      position={position}
      onClick={onClick}
      onPointerOver={() => setHover(true)}
      onPointerOut={() => setHover(false)}
      castShadow
    >
      <boxGeometry args={[0.95, 0.95, 0.95]} />
      <meshStandardMaterial color={hovered ? 'white' : color} />
    </mesh>
  )
}

// 魔方组件
function RubiksCube() {
  const groupRef = useRef()
  const [rotation, setRotation] = useState([0, 0, 0])
  const [selectedFace, setSelectedFace] = useState(null)

  // 创建魔方所有方块
  const cubes = []
  const colors = {
    front: 'red',
    back: 'orange',
    left: 'green',
    right: 'blue',
    top: 'white',
    bottom: 'yellow'
  }

  // 生成3x3x3魔方
  for (let x = -1; x <= 1; x++) {
    for (let y = -1; y <= 1; y++) {
      for (let z = -1; z <= 1; z++) {
        // 跳过中心方块（不可见）
        if (x === 0 && y === 0 && z === 0) continue
        
        // 确定每个面的颜色
        const cubeColors = {}
        if (x === 1) cubeColors.right = colors.right
        if (x === -1) cubeColors.left = colors.left
        if (y === 1) cubeColors.top = colors.top
        if (y === -1) cubeColors.bottom = colors.bottom
        if (z === 1) cubeColors.front = colors.front
        if (z === -1) cubeColors.back = colors.back
        
        cubes.push({
          position: [x, y, z],
          colors: cubeColors
        })
      }
    }
  }

  // 处理点击方块旋转面
  const handleCubeClick = (position, event) => {
    event.stopPropagation()
    
    // 确定点击的是哪个面（简化版，实际需要更精确的碰撞检测）
    const { x, y, z } = event.point
    const absX = Math.abs(x)
    const absY = Math.abs(y)
    const absZ = Math.abs(z)
    
    let face = null
    if (absX > absY && absX > absZ) {
      face = x > 0 ? 'right' : 'left'
    } else if (absY > absX && absY > absZ) {
      face = y > 0 ? 'top' : 'bottom'
    } else {
      face = z > 0 ? 'front' : 'back'
    }
    
    setSelectedFace(face)
    
    // 旋转整个组（简化版，实际应该只旋转选中的面）
    if (face === 'right') setRotation([rotation[0], rotation[1] + Math.PI/2, rotation[2]])
    if (face === 'left') setRotation([rotation[0], rotation[1] - Math.PI/2, rotation[2]])
    if (face === 'top') setRotation([rotation[0] - Math.PI/2, rotation[1], rotation[2]])
    if (face === 'bottom') setRotation([rotation[0] + Math.PI/2, rotation[1], rotation[2]])
  }

  // 平滑旋转动画
  useFrame(() => {
    if (groupRef.current) {
      groupRef.current.rotation.x = THREE.MathUtils.lerp(
        groupRef.current.rotation.x,
        rotation[0],
        0.1
      )
      groupRef.current.rotation.y = THREE.MathUtils.lerp(
        groupRef.current.rotation.y,
        rotation[1],
        0.1
      )
    }
  })

  return (
    <group ref={groupRef}>
      {cubes.map((cube, index) => (
        <Cube
          key={index}
          position={cube.position}
          color={cube.colors[Object.keys(cube.colors)[0]]} // 简化：只显示一个颜色
          onClick={(e) => handleCubeClick(cube.position, e)}
        />
      ))}
    </group>
  )
}

// 主组件
export default function App() {
  return (
    <div style={{ width: '100vw', height: '100vh' }}>
      <Canvas camera={{ position: [5, 5, 5], fov: 50 }}>
        <ambientLight intensity={0.5} />
        <pointLight position={[10, 10, 10]} />
        <RubiksCube />
        <OrbitControls enablePan={false} />
      </Canvas>
    </div>
  )
}